﻿using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form_send : Form
    {
        public string url = "";
        public string post = "";
        public string method = "";
        public string encoding = "";
        public bool isimg = false;

        public static CookieCollection tmpCookies;

        public Form_send()
        {
            InitializeComponent();
            if (tmpCookies == null)
            {
                tmpCookies = new CookieCollection();
            }
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
        }

        private void Form_send_Load(object sender, EventArgs e)
        {
            //if (this.url == "http://qb.qq.com/cgi-bin/qbas_login.cgi")
            //{
            //    this.textBox_pass11.Text = "lemon1020";
            //    this.button_pass.Text = "生成密码";
            //}
            //else if (url == "https://esales.changyou.com/captcha.xhtml?t=")
            //{
            //    url += GetTime();
            //    this.textBox_pass11.Text = "hulala852";
            //}

            this.textBox1.Text = url;
            this.richTextBox_post.Text = post;

            if (this.method == "get")
            {
                this.radioButton_get.Select();
                
            }
            else
            {
                this.radioButton_post.Select();
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void GetPostData(string sb, ref HttpWebRequest request)
        {
            byte[] SomeBytes = null;
            SomeBytes = Encoding.UTF8.GetBytes(sb.ToString());
            request.ContentLength = SomeBytes.Length;
            Stream newStream = request.GetRequestStream();
            newStream.Write(SomeBytes, 0, SomeBytes.Length);
            newStream.Close();
            //string para = sb.ToString();

            //StringBuilder UrlEncoded = new StringBuilder();
            //Char[] reserved = { '?', '=', '&' };
            //byte[] SomeBytes = null;
            //if (para != null)
            //{
            //    int i = 0, j;
            //    while (i < para.Length)
            //    {
            //        j = para.IndexOfAny(reserved, i);
            //        if (j == -1)
            //        {
            //            UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, para.Length - i), System.Text.Encoding.Default));
            //            break;
            //        }
            //        UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, j - i), System.Text.Encoding.Default));
            //        UrlEncoded.Append(para.Substring(j, 1));
            //        i = j + 1;
            //    }
            //    SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString());
            //    request.ContentLength = SomeBytes.Length;
            //    Stream newStream = request.GetRequestStream();
            //    newStream.Write(SomeBytes, 0, SomeBytes.Length);
            //    newStream.Close();
            //}
        }

        private void GetPostData(StringBuilder sb, ref HttpWebRequest request)
        {
            string para = sb.ToString();

            StringBuilder UrlEncoded = new StringBuilder();
            Char[] reserved = { '?', '=', '&' };
            byte[] SomeBytes = null;
            if (para != null)
            {
                int i = 0, j;
                while (i < para.Length)
                {
                    j = para.IndexOfAny(reserved, i);
                    if (j == -1)
                    {
                        UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, para.Length - i), System.Text.Encoding.Default));
                        break;
                    }
                    UrlEncoded.Append(HttpUtility.UrlEncode(para.Substring(i, j - i), System.Text.Encoding.Default));
                    UrlEncoded.Append(para.Substring(j, 1));
                    i = j + 1;
                }
                SomeBytes = Encoding.Default.GetBytes(UrlEncoded.ToString());
                request.ContentLength = SomeBytes.Length;
                Stream newStream = request.GetRequestStream();
                newStream.Write(SomeBytes, 0, SomeBytes.Length);
                newStream.Close();
            }
        }

        private void get_request(string url)
        {
            string strUrl = url;
            Uri URI = new Uri(strUrl);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1;  Embedded Web Browser from: http://bsalsa.com/; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; .NET CLR 1.1.4322; .NET CLR 2.0.50727; CIBA; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            request.CookieContainer = new CookieContainer();

            foreach (System.Net.Cookie cookie in tmpCookies)
            {
                cookie.Domain = URI.Host;
                if (cookie.Value.Length != 0)
                {
                    request.CookieContainer.Add(cookie);
                }
            }

            HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
            foreach (System.Net.Cookie newcookie in myHttpWebResponse.Cookies)
            {
                tmpCookies.Add(newcookie);
            }

            Stream receiveStream = myHttpWebResponse.GetResponseStream();
            if (encoding == "")
            {
                encoding = "utf-8";
            }
            StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.GetEncoding(encoding));
            string temp = readStream.ReadToEnd();
            this.richTextBox1.Text = temp;
            this.webBrowser1.Stop();
            this.webBrowser1.DocumentText = temp;
            this.webBrowser1.Refresh();
        }

        private static string GetTime()
        {
            System.Type type = System.Type.GetTypeFromProgID("MSScriptControl.ScriptControl");
            Object script = System.Activator.CreateInstance(type);
            type.InvokeMember("language", BindingFlags.SetProperty, null, script, new Object[] { "JavaScript" });
            type.InvokeMember("AddCode", BindingFlags.InvokeMethod, null, script, new Object[] { "function test(){ return new Date().toString()}" });
            object o = type.InvokeMember("Run", BindingFlags.InvokeMethod, null, script, new Object[] { "test" }).ToString();

            return o.ToString();
        }

        /// <summary>
        /// fa song
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSend_Click(object sender, EventArgs e)
        {
            post = this.richTextBox_post.Text;
            url = this.textBox1.Text;

            string strUrl = url;
            Uri URI = new Uri(strUrl);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.ContentType = "application/json";
            //request.ContentType = "application/x-www-form-urlencoded";
            //request.ServicePoint.Expect100Continue = false;
            //request.Timeout = 30000;
            //request.KeepAlive = true;
            //request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";

            request.Accept = "*/*";

            //application / json,application / xml,application / xhtml + xml,text / html,text / xml,text / plain
            //request.Headers.Add("UA-CPU", "x86");
            //request.Headers.Add("Accept-Encoding", "gzip, deflate");
            //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1;  Embedded Web Browser from: http://bsalsa.com/; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; .NET CLR 1.1.4322; .NET CLR 2.0.50727; CIBA; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0";
            //request.CookieContainer = new CookieContainer();
            ////cookie
            //foreach (System.Net.Cookie cookie in tmpCookies)
            //{
            //    cookie.Domain = URI.Host;
            //    if (cookie.Value.Length != 0)
            //    {
            //        request.CookieContainer.Add(cookie);
            //    }
            //    else
            //    {
            //        //Console.WriteLine(cookie.ToString());
            //    }
            //}

            //发送方式
            if (this.radioButton_post.Checked == true)
            {
                request.Method = "post";

                //发送数据
                string para = this.post;
                GetPostData(para, ref request);
            }
            else
            {
                request.Method = "get";
            }

            try
            {
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
                foreach (System.Net.Cookie newcookie in myHttpWebResponse.Cookies)
                {
                    tmpCookies.Add(newcookie);
                }

                Stream receiveStream = myHttpWebResponse.GetResponseStream();

                if (isimg)
                {
                    try
                    {
                        MemoryStream dataStream;
                        dataStream = CopyStream(receiveStream);
                        System.Drawing.Image img = null;
                        img = System.Drawing.Image.FromStream(dataStream);
                        this.pictureBox1.Image = img;
                    }
                    catch (Exception ee) { }
                }
                else
                {
                    //Encoding encode = System.Text.Encoding.UTF8;
                    if (encoding == "")
                    {
                        encoding = "utf-8";
                    }
                    StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.GetEncoding(encoding));
                    string temp = readStream.ReadToEnd();
                    this.richTextBox1.Text = temp;
                    //this.webBrowser1 = new WebBrowser();
                    this.webBrowser1.DocumentText = temp;


                    commen.TreeViewAndJson treeViewAndJson = new commen.TreeViewAndJson();
                    treeViewAndJson.BindTreeView(this.treeView1, temp);


                    //if (url == "http://qb.qq.com/cgi-bin/qbas_login.cgi")
                    //{
                    //    //this.webBrowser1 = new WebBrowser();
                    //    Regex r = new Regex(@"\d.*\d");
                    //    Match m = r.Match(temp);
                    //    string s = m.Value.ToString();

                    //    string s1 = "http://qb.qq.com/index_frame.shtml?PcacheTime=" + s + "";
                    //    get_request(s1);
                    //}
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message.ToString());
            }
        }

        private static MemoryStream CopyStream(Stream stream)
        {
            MemoryStream result = new MemoryStream();
            byte[] buffer = new byte[0x1000];
            while (true)
            {
                int size = stream.Read(buffer, 0, 0x1000);
                if (size <= 0)
                {
                    break;
                }
                result.Write(buffer, 0, size);
            }
            result.Seek(0L, SeekOrigin.Begin);
            return result;
        }

      
    }
}